<script setup>
import { ref, onMounted } from 'vue';
import { queryStuApi, addStuApi, queryByIdApi, updateStuApi, deleteStuApi, violApi } from '@/api/stu';
import { queryAllClazzApi } from '@/api/clazz'
import { ElMessage, ElMessageBox } from 'element-plus';

//搜索表单
const searchStus = ref({
  name: '',
  degree: '',
  clazzId: ''
})

const clazzs = ref([]);

const getAllClazz = async () => {
  const result = await queryAllClazzApi();
  if (result.code) {
    clazzs.value = result.data;
  }
}


onMounted(() => {
  search();
  getAllClazz();
})

//学生数据
const stuList = ref([]);
//分页条
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const handleSizeChange = (val) => {
  search();
}
const handleCurrentChange = (val) => {
  search();
}
//搜索
const search = async () => {
  const result = await queryStuApi(searchStus.value.name,
    searchStus.value.degree,
    searchStus.value.clazzId,
    currentPage.value,
    pageSize.value
  )
  if (result.code) {
    stuList.value = result.data.rows;
    total.value = result.data.total;
  }
}
// 清空
const clear = () => {
  searchStus.value = {
    name: '',
    degree: '',
    clazzId: ''
  }
  search();
}
// 学生数据
const stu = ref({
  name: '',
  no: '',
  gender: '',
  phone: '',
  degree: '',
  clazzId: '',
  idCard: '',
  isCollege: '',
  address: '',
  graduationDate: ''
});

// 控制弹窗
const dialogVisible = ref(false)
const dialogTitle = ref('')

//表单校验
const stuFormRef = ref();

//表单校验规则
const addrules = ref({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度应在2到10个字符之间', trigger: 'blur' }
  ],
  no: [
    { required: true, message: '请输入学号', trigger: 'blur' },
    { pattern: /^20\d{8}$/, message: '请输入有效学号', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
  ],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { min: 18, max: 18, message: '请输入有效身份证号', trigger: 'blur' }
  ],
  isCollege: [
    { required: true, message: '请选择', trigger: 'change' },
  ]
});

const genders = ref([{ name: '男', value: 1 }, { name: '女', value: 2 }])
const isColleges = ref([{ name: '是', value: 1 }, { name: '否', value: 0 }])
const degrees = ref([{ name: '初中', value: 1 }, { name: '高中', value: 2 }, { name: '大专', value: 3 }, { name: '本科', value: 4 }, { name: '硕士', value: 5 }, { name: '博士', value: 6 }])

//新增学员
const add = async () => {
  dialogVisible.value = true;
  dialogTitle.value = '新增学员';
  stu.value = {
    name: '',
    no: '',
    gender: '',
    phone: '',
    degree: '',
    clazzId: '',
    idCard: '',
    isCollege: '',
    address: '',
    graduationDate: ''
  }
  if (stuFormRef.value) {
    stuFormRef.value.resetFields();
  }
}
//保存学员
const save = async () => {
  if (!stuFormRef) return
  await stuFormRef.value.validate(async (valid, fields) => {
    if (valid) {//校验通过
      let result;
      if (stu.value.id) {
        result = await updateStuApi(stu.value);
      } else {
        result = await addStuApi(stu.value);
      }
      if (result.code) {
        ElMessage.success('保存成功')
        dialogVisible.value = false;
        search();
      } else {
        ElMessage.error(result.msg);
      }
    } else {//校验失败
      ElMessage.error('表单校验不通过,请检查表单');
    }
  })
}

//查询回显
const edit = async (id) => {
  const result = await queryByIdApi(id);
  if (result.code) {
    dialogVisible.value = true;
    dialogTitle.value = '修改学员';
    stu.value = result.data;
  } else {
    ElMessage.error(result.msg);
  }
}

//删除学员
//删除单个学员
const deleteById = async (id) => {
  ElMessageBox.confirm(
    '您确认删除该员工吗?',
    'Warning',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    const result = await deleteStuApi(id);
    if (result.code) {
      ElMessage.success('删除成功');
      search();
    } else {
      ElMessage.error(result.msg)
    }
  }).catch(() => {
    ElMessage.info('操作已取消');
  })
}
//批量删除学员
const selectIds = ref([]);
const handleSelectionChange = (valArr) => {
  selectIds.value = valArr.map(item => item.id);
}
const deleteByIds = async () => {
  ElMessageBox.confirm(
    '您确认删除该员工吗?',
    'Warning',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    const result = await deleteStuApi(selectIds.value);
    if (result.code) {
      ElMessage.success('删除成功');
      search();
    } else {
      ElMessage.error(result.msg)
    }
  }).catch(() => {
    ElMessage.info('操作已取消');
  })
}

//违纪处理
const dialogViolVisible = ref(false);
const violation = ref({
  score: ''
});
const violid = ref('')

//违纪表单检验
const violFormRef = ref();
//表单校验规则
const violrules = ref({
  score: [
    { required: true, message: '孩子知道错了,就别扣了', trigger: 'blur' },
  ]
});

//添加违纪
const viol = (id) => {
  dialogViolVisible.value = true;
  violation.value = {
    score: ''
  }
  violid.value = id;
  if (violFormRef.value) {
    violFormRef.value.resetFields();
  }
}
//保存违纪
const addviol = async () => {
  if (!violFormRef) return
  await violFormRef.value.validate(async (valid, fields) => {
    if (valid) {//通过    
      const result = await violApi(violid.value, violation.value.score);
      if (result.code) {
        ElMessage.success('相信他会改过自新的');
        dialogViolVisible.value = false;
        search();
      } else {
        ElMessage.error(result.msg);
      }
    } else {//不通过
      ElMessage.error('扣分的时候注意,别啥都往里写')
    }
  })
}


</script>

<template>
  <h1>学员管理</h1>
  <!-- 按钮 -->
  <div class="stuButton">
    <el-button type="primary" @click="add">+ 新增学员</el-button>
    <el-button type="danger" @click="deleteByIds">- 批量删除</el-button>
  </div>

  <!-- 搜索表单 -->
  <div class="search">
    <el-form :inline="true" :model="searchStus" class="demo-form-inline">
      <el-form-item label="姓名">
        <el-input v-model="searchStus.name" placeholder="请输入学生姓名" />
      </el-form-item>
      <el-form-item label="学历">
        <el-select v-model="searchStus.degree" placeholder="请选择" clearable>
          <el-option label="初中" value="1" />
          <el-option label="高中" value="2" />
          <el-option label="大专" value="3" />
          <el-option label="本科" value="4" />
          <el-option label="硕士" value="5" />
          <el-option label="博士" value="6" />
        </el-select>
      </el-form-item>
      <el-form-item label="所属班级">
        <el-select v-model="searchStus.clazzId" placeholder="请选择" clearable>
          <el-option v-for="clazz in clazzs" :label="clazz.name" :value="clazz.id" />
        </el-select>
      </el-form-item>
      <el-form-item id="clbutton">
        <el-button type="primary" @click="search">查询</el-button>
        <el-button type="info" @click="clear">清空</el-button>
      </el-form-item>
    </el-form>
  </div>

  <!-- 学生列表 -->
  <div class="stuFrom">
    <el-table :data="stuList" border style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column prop="name" label="姓名" width="90" align="center" />
      <el-table-column prop="no" label="学号" width="110" align="center" />
      <el-table-column prop="clazzName" label="班级" width="145" align="center">
      </el-table-column>

      <el-table-column prop="gender" label="性别" width="80" align="center">
        <template #default="scope">
          {{ scope.row.gender == 1 ? '男' : '女' }}
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号" width="135" align="center" />
      <el-table-column prop="degree" label="最高学历" width="100" align="center">
        <template #default="scope">
          <span v-if="scope.row.degree == 1">初中</span>
          <span v-else-if="scope.row.degree == 2">高中</span>
          <span v-else-if="scope.row.degree == 3">大专</span>
          <span v-else-if="scope.row.degree == 4">本科</span>
          <span v-else-if="scope.row.degree == 5">硕士</span>
          <span v-else-if="scope.row.degree == 6">博士</span>
          <span v-else>其他</span>
        </template>
      </el-table-column>
      <el-table-column prop="violationCount" label="违纪次数" width="90" align="center" />
      <el-table-column prop="violationScore" label="违纪扣分" width="90" align="center" />
      <el-table-column prop="updateTime" label="最后修改时间" align="center" />
      <el-table-column label="操作" width="200" align="center">
        <template #default="scope">
          <el-button size="small" type="primary" @click="edit(scope.row.id)">编辑</el-button>
          <el-button size="small" type="warning" @click="viol(scope.row.id)">违纪</el-button>
          <el-button size="small" type="danger" @click="deleteById(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40, 50]"
    layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
    @current-change="handleCurrentChange" />

  <!-- 新增/修改表单 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form ref="stuFormRef" :rules="addrules" :model="stu" label-width="80px">
      <!-- 基本信息 -->
      <!-- 第一行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="stu.name" placeholder="请输入学员姓名"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="学号" prop="no">
            <el-input v-model="stu.no" placeholder="请输入学员学号"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select v-model="stu.gender" placeholder="请选择性别" style="width: 100%;">
              <el-option v-for="gender in genders" :label="gender.name" :value="gender.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="stu.phone" placeholder="请输入学院手机号"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第三行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="身份证号" prop="idCard">
            <el-input v-model="stu.idCard" placeholder="请输入身份证号" style="width: 100%;" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否院校" prop="isCollege">
            <el-select v-model="stu.isCollege" placeholder="请选择" style="width: 100%;">
              <el-option v-for="isCollege in isColleges" :label="isCollege.name" :value="isCollege.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第四行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系地址">
            <el-input v-model="stu.address" placeholder="请输入联系地址" style="width: 100%;" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最高学历">
            <el-select v-model="stu.degree" placeholder="请选择" style="width: 100%;">
              <el-option v-for="degree in degrees" :label="degree.name" :value="degree.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第五行 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="毕业时间">
            <el-date-picker v-model="stu.graduationDate" type="date" style="width: 100%;" placeholder="选择日期"
              format="YYYY-MM-DD" value-format="YYYY-MM-DD"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属班级">
            <el-select v-model="stu.clazzId" placeholder="请选择" style="width: 100%;">
              <el-option v-for="clazz in clazzs" :label="clazz.name" :value="clazz.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>

    <!-- 底部按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 违纪表单 -->
  <el-dialog v-model="dialogViolVisible" title="提示" width="500">
    <el-form :model="violation" ref="violFormRef" :rules="violrules">
      <el-form-item label="请输入违纪扣分" :label-width="formLabelWidth" prop="score">
        <el-input v-model="violation.score" autocomplete="off" />
      </el-form-item>
    </el-form>
    <!-- 底部按钮 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogViolVisible = false">取消</el-button>
        <el-button type="primary" @click="addviol">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.stuButton {
  margin: 10px 0;
}

.search {
  margin: 10px 0;
}
</style>